<template>
  <div class="app-container">
    <y-table ref="gridRef" v-bind="listOptions" @toolbar-button-click="toolbarButtonClickEvent">
      <template #editcolumn="{ row, column }">
        <div v-if="!editColumnFlag">
          <el-select v-if="column.field == 'campusName'" size="mini" style="width: 100px" v-model="row['campusCode']"
            @change="
              row['campusName'] = dictCampusList.find(item => item.value === row['campusCode']).name;
            updateById(row, column)">
            <el-option v-for="item in dictCampusList" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
          <el-select v-else-if="column.field === 'isValid'" size="mini" style="width: 80px" v-model="row[column.field]"
            @change="updateById(row, column)">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
          <el-input v-else size="mini" v-model="row[column.field]" @change="updateById(row, column)"></el-input>
        </div>
        <div v-else>
          {{ column.field === 'isValid' ? row[column.field] ? '是' : '否' : row[column.field] }}
        </div>
      </template>
    </y-table>
    <y-form-dialog :title="formOptions.title" ref="dialogFormRef" :form-options="formOptions"
      @confirm="confirmForm"></y-form-dialog>
    <y-form-dialog :title="formOptions.title" ref="dialogInfoRef" :form-options="detailFormConfig"
      @confirm="_ => { }"></y-form-dialog>
    <y-form-dialog :title="formOptions.title" ref="dialogBatchRef" :form-options="batchFormOptions"
      @confirm="batchConfirmForm"></y-form-dialog>
  </div>
</template>

<script>

import {
  getClassList, updateClassField, bathDeleteClass, addClass,
  getMajorByCollegeCode, getTermYear, createCode, updateByIds
} from '@/api/base/class' // 接口



import listMixin from '@/mixins/listMixin'

export default {
  mixins: [listMixin],
  data() {
    return {
      //编辑模式开关
      editColumnFlag: true,
      dictCampusList: [],
      dictCollegeList: [],
      //是否使用
      options: [
        { value: true, label: '是' },
        { value: false, label: '否' }
      ],
      // 表格配置
      listOptions: {
        importConfig: { fileName: "班级导入", module: "BJXXDR" },//导入配置
        exportConfig: { fileName: "班级导出", module: "BJXXDC" },//导出配置
        // 默认查询数据
        defaultQueryData: {
          // form
          form: {},
          // 分页
          page: {
            pageSize: 50
          },
          // 其他查询参数
          params: {}
        },
        // 获取数据方法
        dataMethod: getClassList,
        // 表格配置
        tableOptions: {
          rowConfig: {
            keyField: 'tid'
          },
          toolbarConfig: {
            // 按钮组
            buttons: [
              { name: '新增', code: 'add', status: 'primary', icon: 'vxe-icon-add' },
              { name: '开启编辑模式', code: 'openEdit', status: 'primary', icon: 'vxe-icon-add' },
              { name: '关闭编辑模式', code: 'closeEdit', status: 'primary', icon: 'vxe-icon-add' },
              { name: '批量删除', code: 'batchDelete', status: 'danger', icon: 'vxe-icon-delete' },
              { name: '批量操作班级', code: 'toMajorSubjectPage', status: 'primary', icon: 'vxe-icon-add' },
              { name: '批量修改', code: 'batchUpdate', status: 'primary', icon: 'vxe-icon-add' },
            ],
            // 工具栏
            tools: [
              // { type: 'button', code: 'DivCode', icon: 'vxe-icon-edit', circle: true },
            ]
          },
          // 表格列
          columns: [
            { type: 'checkbox', width: 48, align: 'center', fixed: 'left' },
            { type: 'seq', width: 60, align: 'center', fixed: 'left' },
            { minWidth: 100, field: "campusName", title: "校区", slots: { default: "editcolumn" } },
            { minWidth: 150, field: "collegeName", title: "学院" },
            { minWidth: 100, field: "majorName", title: "专业" },
            { minWidth: 60, field: "grade", title: "年级" },
            { minWidth: 60, field: "schoolingLen", title: "学制" },
            { minWidth: 100, field: "classCode", title: "班级代码" },
            { minWidth: 150, field: "className", title: "班级名称", slots: { default: "editcolumn" } },
            { minWidth: 60, field: "classNo", title: "班级号", visible: false },
            { minWidth: 80, field: "classMax", title: "班级容量", slots: { default: "editcolumn" } },
            { minWidth: 80, field: "classNum", title: "实际人数", slots: { default: "editcolumn" } },
            { minWidth: 100, field: "entranceTime", title: "入学时间", visible: false },
            { minWidth: 100, field: "graduateTime", title: "毕业时间", visible: false },
            { minWidth: 80, field: "eduBkgdLevelCode", title: "学历层次代码", dictCode: "education_background_level", visible: false },
            { minWidth: 80, field: "eduLevelCode", title: "培养层次", dictCode: "education_level", visible: false },
            { minWidth: 80, field: "isValid", title: "是否可用", slots: { default: "editcolumn" } },
            {
              title: '操作',
              width: 130,
              cellRender: {
                name: 'buttons',
                options: [
                  { content: '修改', name: 'edit' },
                  {
                    content: '更多', dropdowns: [
                      { content: '详情', name: 'info' },
                      { content: '删除', name: 'delete' }
                    ]
                  }
                ],
                events: {
                  click: ({ name, row }) => {
                    switch (name) {
                      case 'edit':
                        this.openFormDialog({ row, refName: 'dialogFormRef' })
                        break
                      case 'delete':
                        this.deleteRow({ row, deleteMethod: (row) => this.bathDeleteClass(row.tid) })
                        break
                      case 'info':
                        this.openFormDialog({ row, refName: 'dialogInfoRef' })
                        break
                      default:
                        break
                    }
                  }
                }
              }
            }
          ]
        },
        // 表单配置
        formOptions: {
          items: [
            {
              field: 'collegeCode', title: '学院',
              cascader: ["majorCode"],
              itemRender: {
                name: 'ZSelect',
                props: {
                  dictCode: 'college_list_easy'
                }
              }
            },
            {
              field: "majorCode", title: "专业",
              itemRender: {
                name: 'ZSelect',
                props: {
                  initData: async (formData) => {
                    if (formData.collegeCode) {
                      return await getMajorByCollegeCode(formData.collegeCode)
                    } else {
                      return []
                    }
                  },
                }
              }
            },
            {
              field: "grade", title: "年级", itemRender: {
                name: 'ZSelect', props: {
                  initData: async () => getTermYear(),
                }
              }
            },
            {
              field: 'isValid', title: '启停状态',
              itemRender: {
                name: 'ZSelect',
                props: {
                  initData: async () => [
                    { name: '可用', value: "1" },
                    { name: '停用', value: "0" },
                  ]
                }
              }
            },
            {
              field: 'classCode', title: '班级名称|代码',
              itemRender: {
                name: 'VxeInput'
              }
            }
          ]
        },
      },
      formOptions: {
        title: '班级信息',
        titleWidth: 140,
        items: [
          {
            required: true, field: 'campusCode', title: '校区',
            itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'campus_list'
              }
            }
          },
          {
            required: true, field: 'collegeCode', title: '学院',
            cascader: ["majorCode"],
            itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'college_list_easy'
              }
            }
          },
          {
            required: true, field: "majorCode", title: "专业",
            itemRender: {
              name: 'ZSelect',
              props: {
                initData: async (formData) => {
                  if (formData.collegeCode) {
                    return await getMajorByCollegeCode(formData.collegeCode)
                  } else {
                    return []
                  }
                },
              }
            }
          },
          {
            required: true, field: "grade", title: "年级", itemRender: {
              name: 'ZSelect', props: {
                initData: async () => getTermYear(),
              }
            }
          },
          {
            required: true, field: "classCode", span: 12, title: "班级代码",
            itemRender: {
              name: 'VxeInput',
              events: {
                blur: (slotParams, { name }) => {
                  if (name === 'autoDeptCode'
                    && !slotParams.data.tid
                    && slotParams.data.classCode
                  ) {
                    testRepeat(slotParams.data.classCode).then(res => {
                      if (res.status) {
                        this.$alert('班级代码已存在，请重新输入！', '提示', {
                          confirmButtonText: '确定',
                          callback: action => {
                            this.$set(slotParams.data, 'classCode', '')
                          }
                        })
                      }
                    })
                  }
                }
              }
            }
          },
          {
            field: 'autoDeptCode', span: 12,
            itemRender: {
              name: 'VxeButtonGroup',
              options: [
                { name: 'autoDeptCode', content: '系统自动生成', status: 'primary' }
              ],
              events: {
                click: (slotParams, { name }) => {
                  if (name === 'autoDeptCode'
                    && !slotParams.data.tid
                    && slotParams.data.majorCode
                    && slotParams.data.grade
                  ) {
                    createCode(slotParams.data.majorCode, slotParams.data.grade).then(res => {
                      if (res.status) {
                        this.$set(slotParams.data, 'classCode', res.data.code)
                        this.$set(slotParams.data, 'className', res.data.name)
                        this.$set(slotParams.data, 'classNo', res.data.no)
                      }
                    })
                  }
                }
              }
            }
          },
          {
            required: true, field: "className", title: "班级名称", itemRender: {
              name: 'VxeInput',
            }
          },
          {
            required: true, field: "classNo", title: "班级编号(班)", itemRender: {
              name: 'VxeInput',
            }
          },
          {
            required: true, field: "schoolingLen", title: "学制", itemRender: {
              name: 'ZSelect',
              props: {
                initData: async () => {
                  return [
                    { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, { value: 5 }, { value: 6 }, { value: 7 }, { value: 8 }
                  ]
                },
              }
            }
          },
          {
            required: true, field: "eduLevelCode", title: "培养层次", itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'education_level'
              }
            }
          },
          {
            required: true, field: "eduBkgdLevelCode", title: "学历层次", itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'education_background_level'
              }
            }
          },
          {
            required: true, field: "classMax", title: "班级容量", itemRender: {
              name: 'VxeInput',
              props: {
                type: 'number'
              }
            }
          },
          {
            required: true, field: "classNum", title: "班级实际人数", itemRender: {
              name: 'VxeInput',
              props: {
                type: 'number',
                placeholder: '新生班（请填写班级容量数）,非新生班（请填写实际人数）'
              }
            }
          },
          {
            required: true, field: "entranceTime", title: "入学时间", itemRender: {
              name: 'VxeInput',
              props: {
                type: 'date'
              }
            }
          },
          {
            required: true, field: "graduateTime", title: "毕业时间", itemRender: {
              name: 'VxeInput',
              props: {
                type: 'date'
              }
            }
          },
          {
            field: "isValid", title: "是否可用", itemRender: {
              name: 'VxeSwitch',
              props: {
                openLabel: '是',
                closeLabel: '否'
              }
            }
          },
        ]
      },
      batchFormOptions: {
        title: '批量操作',
        titleWidth: 140,
        items: [
          {
            field: 'campusCode', title: '校区',
            itemRender: {
              name: 'ZSelect',
              props: {
                dictCode: 'campus_list'
              }
            }
          },
          {
            field: 'classNum', span: 13, title: '批量更新班级人数',
            itemRender: {
              name: 'VxeInput',
              props: {
                type: 'number'
              }
            }
          },
          {
            field: 'isValid', title: '启停状态',
            itemRender: {
              name: 'ZSelect',
              props: {
                initData: async () => [
                  { name: '可用', value: 1 },
                  { name: '停用', value: 0 },
                ]
              }
            }
          },
        ]
      }
    }
  },
  computed: {
    detailFormConfig() {
      return {
        ...this.formOptions,
        border: true,
        items: this.formOptions.items.filter(d => d.field).map(({ field, title }) => {
          return { field, title }
        })
      }
    }
  },
  /**
   * 组件挂载时异步执行的方法
   */
  async mounted() {
    // 动态设置查询参数
    // 此处的目的是根据某些条件或逻辑动态地设置组件的查询参数，以便在加载数据前做好准备
    await this.setFormQuery()

    // 加载数据
    // 通过refs引用调用loadData方法来加载数据
    this.$refs.gridRef.loadData()
  },
  methods: {
    /**
     * 工具栏按钮点击事件处理函数
     * @param {Object} event - 事件对象，包含按钮代码
     * 该函数根据点击的工具栏按钮代码，执行不同的操作
     */
    toolbarButtonClickEvent({ code }) {
      switch (code) {
        case 'openEdit':
          // 打开编辑模式
          this.editColumnFlag = false
          break
        case 'closeEdit':
          // 关闭编辑模式
          this.editColumnFlag = true
          break
        case 'add':
          // 执行添加操作，打开表单对话框
          this.openFormDialog({ row: null, refName: 'dialogFormRef' })
          break
        case 'batchDelete':
          // 批量删除
          let checkboxRecords = this.getCheckboxRow()
          if (checkboxRecords.length === 0) {
            this.$message.warning('请先选择要删除的记录')
            return
          }
          this.$confirm('确认删除选中的记录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteById(checkboxRecords)
          })
          break
        case 'batchUpdate':
          // 批量修改
          checkboxRecords = this.getCheckboxRow()
          if (checkboxRecords.length === 0) {
            this.$message.warning('请先勾选班级')
            return
          }
          this.openFormDialog({ row: null, refName: 'dialogBatchRef' })
          break
        default:
          break
      }
    },
    async batchConfirmForm(form) {
      return new Promise((resolve, reject) => {
        form.tids = this.getCheckboxRow().map(item => item.tid)
        updateByIds(form).then(res => {
          if (res.status) {
            this.$message.success(res.message)
            this.$refs.gridRef.loadData()
            resolve(true)
          }
        })
      })
    },
    //提交表单
    async confirmForm(form) {
      return new Promise((resolve, reject) => {
        this.saveOrUpdate(form).then(res => {
          if (res.status) {
            this.$message.success(res.message)
            this.$refs.gridRef.loadData()
            resolve(true)
          }
        })
      })
    },
    // 保存或修改
    saveOrUpdate(form) {
      if (form.tid) {
        return updateClassField(form)
      } else {
        return addClass(form)
      }
    },
    // 修改
    updateById(row) {
      updateClassField(row).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    // 删除
    deleteById(row) {
      bathDeleteClass(row.tid || row.map(item => item.tid).join(',')).then(res => {
        if (res.status) {
          this.$message.success(res.message)
          this.$refs.gridRef.loadData()
        }
      })
    },
    async setFormQuery() {
      // this.listOptions.defaultQueryData.form.pageSize = 50
      // this.listOptions.defaultQueryData.form.pageNum = 1
      this.dictCampusList = await this.getDictItems("campus_list");
      // this.dictCollegeList = await this.getDictItems("college_list");
    },
    getRadioRow() {
      return this.$refs.gridRef.$refs.gridRef.getRadioRecord()
    },
    getCheckboxRow() {
      return this.$refs.gridRef.$refs.gridRef.getCheckboxRecords()
    },
  }
}
</script>

<style lang="scss" scoped></style>
